package com.taoyige.adapter;

import java.util.List;

import org.apache.commons.httpclient.util.DateUtil;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.taoyige.AppConfig;
import com.taoyige.AppContext;
import com.taoyige.AppException;
import com.taoyige.AppManager;
import com.taoyige.R;
import com.taoyige.api.ApiClient;
import com.taoyige.bean.Address;
import com.taoyige.bean.Order;
import com.taoyige.bean.URLs;
import com.taoyige.common.BitmapUtil;
import com.taoyige.common.UIHelper;
import com.taoyige.ui.BuyNowActivity;
import com.taoyige.widget.LoadingDialog;

/**
 * 订单列表Adapter类
 * @author peter
 * @version 1.0
 * @created 2014-11-26
 */
public class ListOrdersAdapter extends BaseAdapter {
	private Context 					context;//运行上下文
	private List<Order> 					listItems;//数据集合
	private LayoutInflater 				listContainer;//视图容器
	private int 						itemViewResource;//自定义项视图源 
	private BitmapUtil bmpUtil;
	static class ListItemView{				//自定义控件集合  
			
			public TextView    order_id;
			public TextView    order_price;
			public TextView  	order_status;
		    public TextView  	order_time;
			public TextView    order_product_title;
			public ImageView    order_product_img;
			
			public Button  order_op1;
			public Button  order_op2;
			
			public RelativeLayout order_detail_rl;
	 }  

	/**
	 * 实例化Adapter
	 * @param context
	 * @param data
	 * @param resource
	 */
	public ListOrdersAdapter(Context context, List<Order> data,int resource) {
		this.context = context;			
		this.listContainer = LayoutInflater.from(context);	//创建视图容器并设置上下文
		this.itemViewResource = resource;
		this.listItems = data;
		this.bmpUtil = new BitmapUtil(BitmapFactory.decodeResource(context.getResources(), 0));
	}
	
	public int getCount() {
		return listItems.size();
	}

	public Object getItem(int arg0) {
		return null;
	}

	public long getItemId(int arg0) {
		return 0;
	}
	
	/**
	 * ListView Item设置
	 */
	public View getView(int position, View convertView, ViewGroup parent) {
		convertView = listContainer.inflate(this.itemViewResource, null);
		/* 节省内存但是动态隐藏按钮时存在bug
		ListItemView  listItemView = null;
		if (convertView == null) {
			convertView = listContainer.inflate(this.itemViewResource, null);
			listItemView = new ListItemView();
			order_id = (TextView)convertView.findViewById(R.id.nopay_order_id_value);
			order_price = (TextView)convertView.findViewById(R.id.nopay_order_money_value);
			order_status = (TextView)convertView.findViewById(R.id.nopay_order_orderstatus_value);
			order_product_title = (TextView)convertView.findViewById(R.id.nopay_order_title);
			order_product_img = (ImageView)convertView.findViewById(R.id.nopay_order_pic);
			order_time = (TextView)convertView.findViewById(R.id.nopay_order_ordertime_value);
			order_detail_rl=(RelativeLayout) convertView.findViewById(R.id.order_detail_rl);
			order_detail_rl.setOnClickListener(checkOrderDetailClickListener);
			convertView.setTag(listItemView);
		}else {
			listItemView = (ListItemView)convertView.getTag();
		}	*/
		 TextView order_id = (TextView)convertView.findViewById(R.id.nopay_order_id_value);
		 TextView order_price = (TextView)convertView.findViewById(R.id.nopay_order_money_value);
		 TextView order_status = (TextView)convertView.findViewById(R.id.nopay_order_orderstatus_value);
		 TextView order_product_title = (TextView)convertView.findViewById(R.id.nopay_order_title);
		 ImageView order_product_img = (ImageView)convertView.findViewById(R.id.nopay_order_pic);
		 TextView order_time = (TextView)convertView.findViewById(R.id.nopay_order_ordertime_value);
		 RelativeLayout order_detail_rl=(RelativeLayout) convertView.findViewById(R.id.order_detail_rl);
		order_detail_rl.setOnClickListener(checkOrderDetailClickListener);
		Order order = listItems.get(position);
		
		order_id.setText(order.getId());
		order_product_title.setText(order.getProduct().getTitle());
		order_product_title.setTag(order);//设置隐藏参数(实体类)
		order_price.setText(order.getTotalPrice()+"");
		order_time.setText(DateUtil.formatDate(order.getTimestamp(), "yyyy-MM-dd hh:mm:ss"));
		
		bmpUtil.loadBitmap(URLs.STATIC_HOST+order.getProduct().getThumbImageUrl().get(0),order_product_img);
		
		
		Button order_op1 = (Button)convertView.findViewById(R.id.order_operation1);
		Button order_op2 = (Button)convertView.findViewById(R.id.order_operation2);
		
		order_detail_rl.setTag(order);
		
		
		//根据订单的status设置按钮不同的值和隐藏按钮 TODO 
		
		order_op2.setTag(order);
		
		switch(order.getStatus()){
		case AppConfig.ORDER_UNPAID:
			order_status.setText(context.getString(R.string.orde_status_unpaid));
			order_op1.setTag(order);
			order_op1 .setOnClickListener(new CancelClickListener(position));
			order_op2 .setOnClickListener(unpaidOrderClickListener);
			break;
		case AppConfig.ORDER_PAID:
			order_status.setText(context.getString(R.string.orde_status_paid));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setText(context.getString(R.string.orde_refund));
			order_op2 .setOnClickListener(paidOrderClickListener);
			break;
			/** UNPAID(1),PAID(2),DELIVERED(3),CHECKED(4),CLOSED(5),DELETED(6),REFUND(7),REFUND_SUCCESS(8),RETURN_GOODS(9),RETURN_GOODS_SUCCESS(10);*/
		case AppConfig.ORDER_DELIVERED:
			order_status.setText(context.getString(R.string.orde_status_delivered));
			order_op1.setText(context.getString(R.string.orderstatusvalue));
			order_op2.setText(context.getString(R.string.orderok));
			order_op1.setTag(order);
			order_op1 .setOnClickListener(trackOrderClickListener);
			order_op2 .setOnClickListener(new RecepitClickListener(position));
			break;
		case AppConfig.ORDER_CHECKED:
			order_status.setText(context.getString(R.string.orde_status_checked));
			order_op2.setText(context.getString(R.string.orde_return_goods));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2 .setOnClickListener(returnGoodsOrderClickListener);
			break;
		case AppConfig.ORDER_CLOSED:
			order_status.setText(context.getString(R.string.orde_status_closed));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_DELETED:
			order_status.setText(context.getString(R.string.orde_status_deleted));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_REFUND:
			order_status.setText(context.getString(R.string.orde_status_refund));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_REFUND_SUCCESS:
			order_status.setText(context.getString(R.string.orde_status_refund_success));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_RETURN_GOODS:
			order_status.setText(context.getString(R.string.orde_status_return_goods));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		case AppConfig.ORDER_RETURN_GOODS_SUCCESS:
			order_status.setText(context.getString(R.string.orde_status_return_goods_scueess));
			order_op1.setVisibility(Button.INVISIBLE);
			order_op2.setVisibility(Button.INVISIBLE);
			break;
		}
		
		
		
		
		return convertView;
	}
	
	class CancelClickListener implements OnClickListener{

		private int position;
		public CancelClickListener(int position){
			this.position=position;
		}
		@Override
		public void onClick(final View v) {
			final Order o = (Order) v.getTag();

			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.msg_order_cancel_title);
			builder.setMessage(R.string.msg_order_cancel_msg);
			builder.setPositiveButton(R.string.sure,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							final  LoadingDialog loading = new LoadingDialog(context);
							final Handler handler = new Handler() {
								public void handleMessage(Message msg) {
									if (loading != null)
										loading.dismiss();
									if (msg.what == 1 ) {
										if(msg.obj!=null){
											Order od=(Order) msg.obj;
											if(od.getResult().getErrorCode()==200){
												//更新数据
												removeItem(position);
												UIHelper.ToastMessage(context, "已经取消该订单");
											}else{
												UIHelper.ToastMessage(context, "取消订单失败，请重试!");
											}
												
										}else{
											((AppException) msg.obj).makeToast(v.getContext());
										}
									} else{
										UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.app_run_code_error));
									}
									
								}
							};
							loading.show();
							
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										Order  order= ((AppContext)context.getApplicationContext()).orderCancel(o.getId(), o.getUserID());
										if(order!=null&&order.getResult().getErrorCode()==200){
											msg.what = 1;
											msg.obj = order;
										}else{
											msg.what = -1;
											msg.obj = null;
										}
									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
									handler.sendMessage(msg);
								}
							}.start();
						}
					});
			builder.setNegativeButton(R.string.cancle,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
			
		}
		
	}
	
	private View.OnClickListener unpaidOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Order o = (Order) v.getTag();
			UIHelper.showBuyNow(v.getContext(), o);
		}
	};
	
	private View.OnClickListener paidOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_return_goods_refund));
		}
	};
	
	private View.OnClickListener trackOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Order o = (Order) v.getTag();
			UIHelper.showOrderTrack(v.getContext(), o.getId(),o.getUserID());
		}
	};
	
	class RecepitClickListener implements OnClickListener{

		private int position;
		public RecepitClickListener(int position){
			this.position=position;
		}
		@Override
		public void onClick(final View v) {
			final Order o = (Order) v.getTag();

			AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
			builder.setIcon(android.R.drawable.ic_dialog_info);
			builder.setTitle(R.string.msg_order_recepit_title);
			builder.setMessage(R.string.msg_order_recepit_msg);
			builder.setPositiveButton(R.string.sure,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							final  LoadingDialog loading = new LoadingDialog(context);
							final Handler handler = new Handler() {
								public void handleMessage(Message msg) {
									if (loading != null)
										loading.dismiss();
									if (msg.what == 1 ) {
										if(msg.obj!=null){
											Order od=(Order) msg.obj;
											if(od.getResult().getErrorCode()==200){
												removeItem(position);
												UIHelper.ToastMessage(context, "已经确认收货");
											}else{
												UIHelper.ToastMessage(context, "确认收货失败，请重试!");
											}
												
										}else{
											((AppException) msg.obj).makeToast(v.getContext());
										}
									} else{
										UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.app_run_code_error));
									}
									
								}
							};
							loading.show();
							
							new Thread() {
								public void run() {
									Message msg = new Message();
									try {
										Order  order= ((AppContext)context.getApplicationContext()).orderRecepit(o.getId(), o.getUserID());
										if(order!=null&&order.getResult().getErrorCode()==200){
											msg.what = 1;
											msg.obj = order;
										}else{
											msg.what = -1;
											msg.obj = null;
										}

									} catch (AppException e) {
										e.printStackTrace();
										msg.what = -1;
										msg.obj = e;
									}
									handler.sendMessage(msg);
								}
							}.start();
						}
					});
			builder.setNegativeButton(R.string.cancle,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.show();
			
		}
			
	};
	
	private View.OnClickListener returnGoodsOrderClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			UIHelper.ToastMessage(v.getContext(), v.getContext().getString(R.string.user_return_goods_refund));
		}
	};
	
	private View.OnClickListener checkOrderDetailClickListener = new View.OnClickListener() {
		public void onClick(View v) {
			Order o = (Order) v.getTag();
			UIHelper.showOrderDetail(v.getContext(), o.getId(),o.getUserID());
		}
	};
	
	  private void removeItem(int position){
		  	listItems.remove(position);
	        this.notifyDataSetChanged();
	    }
	  
	  private void refreshItem(){
	        this.notifyDataSetChanged();
	    }
	  
}